import axios from 'axios'
import router from '../router'
import { getToken, removeToken } from '../utils/auth'
import { Notification } from 'element-ui'
import setting from '../settings'

const ajax = axios.create({
  timeout: 60000
})
// http request 拦截器
ajax.interceptors.request.use(
  config => {
    const userSession = getToken()
    if (userSession) {
      config.headers.Authorization = `Bearer ${userSession}`
      config.headers['X-Token'] = `Bearer ${userSession}`
    }
    return config
  },
  err => {
    console.log(err)
    return Promise.reject(err)
  })

// http response 拦截器
ajax.interceptors.response.use(
  response => {
    return response
  },
  error => {
    if (error.response) {
      Notification.error({
        title: '错误',
        message: error.response.data.msg || error.response.statusText || error.response.data.message || error.response.data
      })
      switch (error.response.status) {
        case 401:
          if (getToken()) removeToken()
          router.push({
            path: '/login',
            query: {
              redirect: router.currentRoute.fullPath
            }
          })
          break
      }
    }
    return Promise.reject(error.response)
  })

export const setAjaxURL = (app) => {
  ajax.defaults.baseURL = `${setting.baseURL}/${app.appApi}/`
}
export default ajax
